<template>
    <div class="question-import" v-loading="loading">
        <el-row>
            <el-col :span="12">
                <el-upload
                        ref="upload"
                        class="upload-demo"
                        action=""
                        :on-change="handleChange"
                        :on-exceed="handleExceed"
                        :on-remove="handleRemove"
                        :file-list="fileListUpload"
                        :limit="limitUpload"
                        :auto-upload="false">
                    <el-button type="primary" icon="el-icon-upload2" size="mini">点击选择</el-button>
                </el-upload>
            </el-col>
            <el-col :span="12" style="text-align: right">
                <el-link type="primary" :href="download_link" target="_blank">下载模板</el-link>
                <el-button size="mini" class="ml10" type="primary" icon="el-icon-check" v-if="list && list.length>0" @click="save" :loading="saveLoading">执行导入</el-button>
            </el-col>
        </el-row>

        <div style="overflow: auto;height: 500px;width: 100%" v-if="list && list.length>0">
            <table class="ikd-input-table" style="width: 100%;" cellspacing="1" cellpadding="8">
                <thead>
                <th nowrap>序号</th>
                <th nowrap>商品编号</th>
                <th nowrap>商品名称</th>
                <th nowrap>规格编号</th>
                <th nowrap>供货价</th>
                <th nowrap>批发价</th>
                <th nowrap>建议售价</th>
                <th nowrap>联盟商批发价</th>
                <th nowrap>联盟商建议售价</th>
                </thead>
                <tbody>
                <tr v-for="(item, idx) in list" :key="idx">
                    <td nowrap>
                        {{idx+1}}
                    </td>
                    <td>
                        <el-input v-model="item.id" size="mini" type="number" />
                    </td>
                    <td>
                        <el-input v-model="item.name" size="mini" />
                    </td>
                    <td>
                        <el-input v-model="item.skuId" type="number" size="mini" />
                    </td>
                    <td>
                        <el-input v-model="item.supplyPrice" size="mini" type="number" />
                    </td>
                    <td>
                        <el-input v-model="item.wholesalePrice" size="mini" type="number" />
                    </td>
                    <td>
                        <el-input v-model="item.salePrice" size="mini" type="number" />
                    </td>
                    <td>
                        <el-input v-model="item.wholesalePrice2" size="mini" type="number" />
                    </td>
                    <td>
                        <el-input v-model="item.salePrice2" size="mini" type="number" />
                    </td>
                </tr>

                </tbody>
            </table>
        </div>


    </div>
</template>
<script>
    import {
        productImport
    } from '../../api/product';
    export default {
        name: 'product-import',
        components: {
        },
        computed:{
            download_link(){
                return "http://ht.350yc.com/product_import.xlsx";
            }
        },
        data() {
            return {
                memberForm: {
                    is_select: true
                },
                parentId: undefined,
                parentMobile: undefined,
                dialogMemberVisible: false,
                classroom_id: 0,
                loading: false,
                fetchSuccess: true,
                fileTemp: null,
                fileListUpload: [],
                limitUpload: 1,
                list: [],
                saveLoading: false,
                header: [],
                current_header: {
                    text: "",
                    field: undefined
                },
                all_field: [
                    {
                        field: "id",
                        name: "商品编号",
                    },
                    {
                        field: "name",
                        name: "商品名称",
                    },
                    {
                        field: "skuId",
                        name: "规格编号",
                    },
                    {
                        field: "supplyPrice",
                        name: "供货价",
                    },
                    {
                        field: "wholesalePrice",
                        name: "批发价",
                    },
                    {
                        field: "salePrice",
                        name: "建议售价",
                    },
                    {
                        field: "wholesalePrice2",
                        name: "联盟商批发价",
                    },
                    {
                        field: "salePrice2",
                        name: "联盟商建议售价",
                    }
                ]
            }
        },
        created() {
        },
        methods: {
            select() {
                this.dialogMemberVisible = true;
            },
            okSelectMember(item) {
                this.parentId = item.id;
                this.parentMobile = item.mobile;
                this.dialogMemberVisible = false;
            },
            handleChange(file, fileList){
                this.fileTemp = file.raw;
                if(this.fileTemp){
                    var index = this.fileTemp.name.lastIndexOf(".");
                    var suffix = this.fileTemp.name.substr(index+1);

                    if(suffix !== "xls" && suffix !== "xlsx") {
                        this.$message({
                            type:'warning',
                            message:'附件格式错误，请删除后重新上传！'
                        })
                    } else {
                        this.importfxx(this.fileTemp);
                    }
                } else {
                    this.$message({
                        type:'warning',
                        message:'请上传附件！'
                    })
                }
            },
            handleRemove(file,fileList){
                this.fileTemp = null
            },
            handleExceed(files, fileList) {
                this.$message({
                    type:'warning',
                    message:'超出最大上传文件数量的限制！'
                })
            },
            importfxx(obj) {
                this.file = event.currentTarget.files[0];

                let rABS = false; //是否将文件读取为二进制字符串
                let f = this.file;

                let reader = new FileReader();

                let _this = this;
                FileReader.prototype.readAsBinaryString = function(f) {
                    let binary = "";
                    let rABS = false; //是否将文件读取为二进制字符串
                    let pt = this;
                    let wb; //读取完成的数据
                    let outdata;
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        let bytes = new Uint8Array(reader.result);
                        let length = bytes.byteLength;
                        for (let i = 0; i < length; i++) {
                            binary += String.fromCharCode(bytes[i]);
                        }
                        //此处引入，用于解析excel
                        let XLSX = require("xlsx");
                        if (rABS) {
                            wb = XLSX.read(btoa(fixdata(binary)), {
                                //手动转化
                                type: "base64"
                            });
                        } else {
                            wb = XLSX.read(binary, {
                                type: "binary"
                            });
                        }
                        //读取第一个sheet
                        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

                        _this.$refs.upload.clearFiles();

                        _this.header = [];
                        if(outdata && outdata.length > 0) {
                            outdata.forEach((item)=>{
                                let id = parseInt(item['商品编号']) || 0;
                                let skuId = parseInt(item['规格编号']) || 0;

                                if(id > 0 && skuId > 0) {
                                    _this.list.push(
                                        {
                                            "id": id,
                                            "name": item['商品名称'],
                                            "skuId": skuId,
                                            "supplyPrice": parseFloat(item['供货价']) || 0,
                                            "wholesalePrice": parseFloat(item['批发价']) || 0,
                                            "salePrice": parseFloat(item['建议售价']) || 0,
                                            "wholesalePrice2": parseFloat(item['联盟商批发价']) || 0,
                                            "salePrice2": parseFloat(item['联盟商建议售价']) || 0,
                                        }
                                    )

                                }
                            })
                            // console.log(_this.list)
                            // let key = Object.keys(outdata[0]);
                            // key.forEach((item)=>{
                            //     _this.header.push({
                            //         text: item,
                            //         field: undefined,
                            //     })
                            // })
                            // _this.list = outdata;
                        }
                    };
                    reader.readAsArrayBuffer(f);
                };
                if (rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            },
            save() {
                // console.log(this.list);
                // return false;
                this.$confirm('确定导入?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        this.saveLoading = true;
                        productImport({
                            items: this.list,
                        })
                            .then(() => {
                                this.saveLoading = false;
                                this.list = [];
                                this.$message.success("商品已导入");
                                this.$emit('okCreate');
                            }).catch((err)=>{
                            this.saveLoading = false;
                        })
                    }).catch(()=>{});

            },
            getBindField(item) {
                let field = "";
                if(item.field) {
                    this.all_field.forEach((it)=>{
                        if(it.field == item.field) {
                            field = it.name;
                            return false;
                        }
                    })
                }

                return field;
            },
            bind(header) {
                this.current_header = header;
            },
            download() {

            }
        }
    }
</script>